<?php
namespace mvc\web;

class Pagination
{
    public $page;
    public $total;
    public $offset;
    public $limit;

    public $pageTotal;

    public function __construct($total, $page, $limit=20)
    {
        $this->limit = $limit;
        $this->page = intval($page);
        $this->total = $total;

        $this->pageTotal = ceil($this->total / $this->limit);
        $this->offset = ($this->getPage() - 1) * $this->limit;
    }

    public function getPage()
    {
        if($this->page == null || $this->page < 1) {
            return 1;
        }

        if($this->page > $this->pageTotal) {
            return $this->pageTotal;
        }

        return $this->page;
    }

    public function getLimit()
    {
        return $this->limit;
    }

    public function getOffset()
    {
        return $this->offset;
    }

    public function render()
    {
        $url = $_SERVER['REQUEST_URI'];

        $sep = '?';
        if (strpos($url, '?') !== false) {
            $sep = '&';
        }

        $html = '';
        if ($this->pageTotal > 1) {
            $html = '<ul class="page">';

            for($i = 1; $i <= $this->pageTotal; $i++) {
                $active = $this->getPage() == $i ? 'class="active"' : '';
                $html .= "<li $active><a href='{$url}{$sep}page={$i}'>$i</a></li>";
            }

            $html .= '<ul>';
        }

        return $html;
    }
}